<?php
namespace App\Utils;

use Overtrue\EasySms\EasySms;

class Sms{

    private $app;

    public function __construct()
    {
        $this->app = new EasySms(config('sms'));
    }

    /**
     * @param $phone
     * @param $tpl
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function send($phone,array $data) {
        if(!Reg::checkPhone($phone)) {
            throw new \Exception('非法的手机号码');
        }
        try{
            $this->app->send(strval($phone) , $data);
            return true;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * @param $phone
     * @param $tpl
     * @param array $data
     * @param null $closure
     * @return bool
     */
    public function sendWithoutCheck($phone,$tpl, array $data, $closure = null) {
        if(Reg::checkPhone($phone)) {
            $res = $this->app->sendSms(strval($phone) , $tpl, $data);
            if($res->code == 'Ok'){
                return true;
            }
            if($closure instanceof \Closure){
                return $closure($res->Code);
            }
        }
    }
}
